package com.example.screenprojection.Display;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.ViewTreeObserver;
import android.view.WindowManager;

import com.example.screenprojection.Socket.BitmapClientRunnable;
import com.example.screenprojection.R;
import com.example.screenprojection.Socket.TouchClientRunnable;
import com.example.screenprojection.Utils.MyUtils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import androidx.appcompat.app.AppCompatActivity;

public class DisplayActivity extends AppCompatActivity {

    private static final String TAG = "DisplayActivity";
    private DisplayView displayView;
    private BitmapClientRunnable bitmapClientRunnable;


    private void InitView() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        displayView = (DisplayView) findViewById(R.id.displayView);
        displayView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                displayView.setViewWidth(displayView.getWidth());
                displayView.setViewHeight(displayView.getHeight());
                displayView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
        bitmapClientRunnable = new BitmapClientRunnable();
        bitmapClientRunnable.setIp(MyUtils.getLocalAddress());
        bitmapClientRunnable.setPort(MyUtils.bitmapSocketPort);
        bitmapClientRunnable.setListener(bitmapClientListener);
        MyUtils.ExecuteRunnable(bitmapClientRunnable);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);
        InitView();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            MyUtils.setKeyCode(keyCode);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    BitmapClientRunnable.ClientListener bitmapClientListener = new BitmapClientRunnable.ClientListener() {
        @Override
        public void onClientConnect() {

        }

        @Override
        public void onClientClose() {

        }

        @Override
        public void onClientReceiveBitmap(Bitmap bitmap, int width, int height) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    displayView.setBitmap(bitmap, width, height);
                }
            });
        }
    };
}